package cn.com.xf.web.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.http.HttpServlet;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.com.xf.web.XFContainsTool;

/**
 * @author Administrator
 * 
 */
public class InitSystemServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	Log log = LogFactory.getLog(InitSystemServlet.class);

	@Override
	public void init(ServletConfig config) {
		ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(config
				.getServletContext());
		XFContainsTool.setApplicationContext(applicationContext);
		try {
			connOracleTest();
			// connOracleA6Test();
		} catch (Exception e) {
			log.warn("数据库连接测试", e);
		}
	}

	private void connTest() throws Exception {
		log.warn("开始数据库连接...");
		DataSource dataSource = (DataSource) XFContainsTool.lookup("dataSource");
		JdbcTemplate temp = new JdbcTemplate(dataSource);
		log.warn("连接对象：" + temp.getDataSource().getConnection());
		String sql = "select count(*) from auth_user";
		Integer count = temp.queryForInt(sql);

		if (count != null && count > 0) {
			log.warn("数据库连接成功！共有用户：" + count + "位");
		} else {
			log.warn("数据库连接失败！");
		}
	}

	private void connOracleTest() throws Exception {
		System.out.println("开始数据库连接Oracle...");
		DataSource dateSourceOracle = (DataSource) XFContainsTool.lookup("dateSourceOracle");
		JdbcTemplate temp = new JdbcTemplate(dateSourceOracle);
		log.warn("连接对象：" + temp.getDataSource().getConnection());
		System.out.println("连接对象：" + temp.getDataSource().getConnection());
		String sql = "select count(*) from tbl_oa_auth_user";
		Integer count = temp.queryForInt(sql);

		if (count != null && count > 0) {
			log.warn("数据库连接成功！共有用户：" + count + "位");
			System.out.println("数据库连接成功！共有用户：" + count + "位");
		} else {
			log.warn("数据库连接失败！");
			System.out.println("数据库连接成功！共有用户：" + count + "位");
		}
	}

	private void connOracleA6Test() throws Exception {
		System.out.println("开始数据库连接dateSourceA6...");
		DataSource dateSourceOracle = (DataSource) XFContainsTool.lookup("dateSourceA6");
		JdbcTemplate temp = new JdbcTemplate(dateSourceOracle);
		log.warn("连接对象：" + temp.getDataSource().getConnection());
		System.out.println("连接对象dateSourceA6：" + temp.getDataSource().getConnection());
		String sql = "select count(*) from ts_user";
		Integer count = temp.queryForInt(sql);

		if (count != null && count > 0) {
			log.warn("数据库连接成功dateSourceA6！共有用户：" + count + "位");
			System.out.println("数据库连接成功dateSourceA6！共有用户：" + count + "位");
		} else {
			log.warn("数据库连接失败dateSourceA6！");
			System.out.println("数据库连接成功dateSourceA6！共有用户：" + count + "位");
		}
	}
}
